package com.example.spring_secutity.filter;


import com.example.spring_secutity.entity.SecurityUser;
import com.example.spring_secutity.entity.User;
import com.example.spring_secutity.util.JWTAuth;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.security.sasl.AuthenticationException;
import java.io.IOException;
import java.util.Arrays;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("xiaoxiao");

        System.out.println("token: "+ token);

        if (StringUtils.isNullOrEmpty(token)){
            //没有token,就放行
            filterChain.doFilter(request,response);
            return;
        }else{

            String userId = JWTAuth.parseJWTSubject(token);
            if (StringUtils.isNullOrEmpty(userId)){
                throw  new AuthenticationException("非法token");
            }

            //redis中检查该id的用户是否已经登录过,判断token是否过期
            //此处应该为登录时存入redis 的用户及权限信息
            // 因暂时未整合redis,暂时new一个临时用户替代
            User user =new User();
            user.setUsrId(6L);
            user.setUsrName("admin");
            SecurityUser securityUser =new SecurityUser(user, Arrays.asList("admin","normal","test"));

            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(securityUser,null,securityUser.getAuthorities());

            //放回上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            System.out.println("-----------------JwtRequestFilter");
            filterChain.doFilter(request,response);

        }
    }
}
